<template>
  <div>
    <!-- 表格部分 -->
    <el-table
      ref="singleTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      fit
      highlight-current-row
      :summary-method="getSummaries"
      show-summary
      :height="tableHeight"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      @current-change="handleCurrentChange"
       @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
       <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="序号"
        prop="no"
        align="center"
        width="80"
      />
      <el-table-column
        label="生成状态"
        align="center"
      >
        <template slot-scope="{row}">
          <span>{{ row.status | statusFilter() }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位编码"
        prop="agencyCode"
        align="center"
      />
      <el-table-column
        label="单位名称"
        prop="agencyName"
        align="center"
      />
      <el-table-column
        label="月份"
        prop="month"
        align="center"
      />
      <el-table-column
        label="应发工资"
        prop="shouldSalary"
        align="center"
      >
        <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.shouldSalary).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="实发工资"
        prop="realSalary"
        align="center"
      >
      <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.realSalary).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="发放人数"
        prop="personCount"
        align="center"
      />
    </el-table>
    <!--分页部分-->
    <div class="size">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <!-- <el-row v-if="tabPane === '2'">
      <el-col :span="4">
        <span style="margin: 10px; display: inline-block;">人员工资明细列表:</span>
      </el-col>
      <el-col :offset="16" :span="4">
        <el-button
          size="small"
          class="filter-item"
          style="margin:10px; float: right;"
          type="primary"
          icon="el-icon-full-screen"
          @click="fullscreen"
        />
      </el-col>
    </el-row>
    表格部分
    <el-table
      v-if="tabPane === '2'"
      ref="personTable"
      v-loading="personListLoading"
      :data="personList"
      :stripe="true"
      fit
      :height="tableHeight"
      style="width: 100%;"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
     
      <el-table-column
        label="序号"
        prop="index"
        align="center"
        width="80"
        fixed
      />
      <el-table-column
        label="工资月份"
        prop="currentMonth"
        align="center"
        fixed
      />
      <el-table-column
        label="科室"
        prop="deptId"
        align="center"
        fixed
      >
        <template slot-scope="{row}">
          <span>{{ row.deptId | deptNameFilter(that) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="身份证号"
        prop="idenNo"
        align="center"
        min-width="180"
        fixed
      />
      <el-table-column
        label="姓名"
        prop="personName"
        align="center"
        fixed
      />
      <el-table-column
        v-for="item in columnNames"
        :key="item.split('_')[0]"
        :label="item.split('_')[0] | salaryNameFilter(that)"
        align="center"
        min-width="150"
      >
        <template slot-scope="{row}">
          <div style="float: right;">
            <span>{{ Number(row[item.split('_')[0]]).toFixed(2) }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    分页部分
    <div class="size">
      <pagination
        v-if="tabPane === '2'"
        :total="personTotal"
        :page.sync="personListQuery.page"
        :limit.sync="personListQuery.limit"
        @pagination="getPersonList"
      />
    </div> -->
    <!--  全屏  -->
    <!-- <div v-if="isFullScreen" class="full-screen">
      <el-row v-if="tabPane === '2'">
        <el-col :span="4">
          <span style="margin: 10px; display: inline-block;">人员工资明细列表:</span>
        </el-col>
        <el-col :offset="16" :span="4">
          <el-button
            size="small"
            class="filter-item"
            style="margin:10px; float: right;"
            type="primary"
            icon="el-icon-full-screen"
            @click="exitFullscreen"
          />
        </el-col>
      </el-row>
      表格部分
      <el-table
        v-if="tabPane === '2'"
        v-loading="personListLoading"
        :data="personList"
        :stripe="true"
        fit
        :height="tableFullScreenHeight"
        style="width: 100%;"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      >
        <template slot="empty">
          <tableEmpty />
        </template>
        <el-table-column
          label="序号"
          prop="index"
          align="center"
          width="80"
          fixed
        />
        <el-table-column
          label="工资月份"
          prop="currentMonth"
          align="center"
          fixed
        />
        <el-table-column
          label="科室"
          prop="deptId"
          align="center"
          fixed
        >
          <template slot-scope="{row}">
            <span>{{ row.deptId | deptNameFilter(that) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="身份证号"
          prop="idenNo"
          align="center"
          min-width="180"
          fixed
        />
        <el-table-column
          label="姓名"
          prop="personName"
          align="center"
          fixed
        />
        <el-table-column
          v-for="item in columnNames"
          :key="item.split('_')[0]"
          :label="item.split('_')[0] | salaryNameFilter(that)"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <div style="float: right;">
              <span>{{ Number(row[item.split('_')[0]]).toFixed(2) }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      分页部分
      <div class="size">
        <pagination
          v-if="tabPane === '2'"
          :total="personTotal"
          :page.sync="personListQuery.page"
          :limit.sync="personListQuery.limit"
          @pagination="getPersonList"
        />
      </div>
    </div> -->
    <uploadLoad v-if="upload_load" ref="uploadLoadSuccess" :params="listQuery" :agency-bank-lists="agencyBankLists " :object="object" :api="'getProgress'" @close="uploadClose" />
  </div>
</template>

<script>
import uploadLoad from './uploadLoad'
import {
  queryColumnName,
  querySalaryNameDict
} from '@/api/unitSalaryReport/unitSalaryReport'
import {
  queryGenerateBankDataPage,
  queryPersonSalaryInfoPage,
  uploadBankData,
  ungenerateBankData,
  generateBankData,
  getProgress
} from '@/api/generateSalaryData/generateBankData'
import { getDepartmentList } from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
import Pagination from '@/components/Pagination'
import tableEmpty from '@/components/table/empty'
import { exportSalaryData } from '@/api/baseInfo'

export default {
  name: 'IsGenerateBankDataChildren',
  components: {
    Pagination,
    tableEmpty,
    uploadLoad
  },
  filters: {
    deptNameFilter(value, that) {
      const deptNames = that.deptNames
      for (const item of deptNames) {
        if (value === item.code) {
          return item.name
        }
      }
    },
    // 工资项滤器
    salaryNameFilter(value, that) {
      const salaryNames = that.salaryNames
      for (const item of salaryNames) {
        if (item.value === value) {
          return item.key
        }
      }
    },
    // 生成状态
    statusFilter(type) {
      if (type === '0') {
        return '未生成'
      } else if (type === '1') {
        return '已上传'
      } else if (type === '2') {
        return '已生成未上传'
      }
    }
  },
  props: ['tabPane'],
  data() {
    return {
      upload_load: false,
      isFullScreen: false,
      tableHeight: null,
      tableFullScreenHeight: null,
      treeShow: false,
      that: this,
      listLoading: true,
      list: [],
      total: 0,
      selected_list:[],
      listQuery: {
        api:'getProgress',
        page: 1,
        limit: 500
      },
      object: {},
      agencyId: '',
      salaCardBank: '',
      columnNames: [], // 动态表头
      salaryNames: [],
      deptNames: [],
      personListLoading: true,
      personList: [],
      personTotal: null,
      personListQuery: {
        page: 1,
        limit: 200
      },
      agencyBankLists: [],
      ifShowMessage: false,
      progressType: ''
    }
  },
  watch: {
    agencyId(newValue, oldValue) {
      if (newValue && this.tabPane === '2') {
        this.getColumnNames(newValue)
        this.getSalaryName(newValue)
        this.getDepartment(newValue)
        this.handlePersonFilter(newValue)
      }
    },
    list(val) {
      this.doLayout()
    },
    personList(val) {
      this.doPersonLayout()
    }
  },
  mounted() {
    this.getTbHeight()
    this.getTbFullScreenHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
    window.addEventListener('resize', this.getTbFullScreenHeight)
  },
  created() {
    this.agencyId = ''
    this.listQuery.tabPane = this.tabPane
    this.handleFilter()
  },
  methods: {
    show(type) {
      if ((this.list && this.list.length === 0) || !this.list) {
        this.$message({
          showClose: true,
          message: '无可生成数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      const h = this.$createElement;
      this.$msgbox({
          title: '消息',
          message: h('span', null, [
            h('span', {class:'messagestyle'}, '当前上传单位数'),
            h('span', null, '\u3000:\u3000'+this.object.agencyCount ),
            h('br', null,),
            h('span', {class:'messagestyle'}, '人数'),
            h('span', null, '\u3000:\u3000'+this.object.personCount),
            h('br', null,),
            h('span', {class:'messagestyle'}, '当前上传金额'),
            h('span', null, '\u3000:\u3000'+Number(this.object.sumRealSalary).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") )
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              done();
              this.ifShowMessage = false
              this.upload_load = true
              this.progressType = type
              if (type === 'upLoad') {
                this.upload() // 进度条同时，调用接口
              }
              if (type === 'generate') {
                this.generate() // 进度条同时，调用接口
              }
            } else {
              done();
            }
          }
        }).then(action => {
          done();
          this.$message({
            type: 'info',
            message: 'error: ' + action
          });
        });

    },
    getProgresss() {
        getProgress(this.listQuery).then(res => {
          this.object = res.data[0]
          
        })
    },
    // 进度条走完，关闭弹窗，调用展示提示信息的方法
    uploadClose() {
      this.upload_load = false
      this.getMessage()
    },
    // 展示附件返回信息
    getMessage() {
      if (this.ifShowMessage) { // 成功
        this.$message({
          message: this.progressType === 'upLoad' ? '上传成功' : '生成成功',
          type: 'success',
          showClose: true,
          duration: 4000
        })
        this.handleFilter()
        this.$parent.handleUploadBtnLoading()
      }
    },
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singleTable.doLayout()
      })
    },
    doPersonLayout() {
      this.$nextTick(() => {
        this.$refs.personTable.doLayout()
      })
    },
    getTbHeight() {
      // if (this.tabPane === '2') {
      //   this.tableHeight = window.innerHeight / 2 - 166
      // } else {
        this.tableHeight = window.innerHeight - 230
      // }
    },
    getTbFullScreenHeight() {
      this.tableFullScreenHeight = window.innerHeight - 140
    },
    handleFilter() {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.listQuery.agencyId = this.agencyId
      this.getList()
    },
    handlePersonFilter(newValue) {
      this.personListQuery.page = 1
      this.personListQuery.limit = 200
      this.personListQuery.agencyId = newValue
      this.getPersonList()
    },
    getList() {
      
      this.listLoading = true
      queryGenerateBankDataPage(this.listQuery).then(res => {
        this.$emit('checkloadCallback')
        this.list = res.data.rows
        this.total = res.data.total
        this.listLoading = false
        if (this.list && this.list.length && this.list.length > 0) {
          //this.setCurrent(true)
        } else {
          //this.setCurrent(false)
          this.agencyId = ''
          this.personList = []
          this.personTotal = null
          this.personListLoading = false
        }
      })
    },
    getPersonList(newValue) {
      this.personListLoading = true
      queryPersonSalaryInfoPage(this.personListQuery).then(res => {
        this.personList = res.data.rows
        this.personTotal = res.data.total
        this.personListLoading = false
      })
    },
    getSalaryName(agencyId) {
       this.personListQuery.agencyId = agencyId
      // 查询工资项名称
      querySalaryNameDict(this.personListQuery).then(res => {
        this.salaryNames = res.data
      })
    },
    getColumnNames(agencyId) {
      this.personListQuery.agencyId = agencyId
      // 查询工资项字段
      queryColumnName(this.personListQuery).then(res => {
        this.columnNames = res.data
      })
    },
    getDepartment(agencyId) {
      // 查询部门名称
      getDepartmentList({ agencyId: agencyId }).then(res => {
        this.deptNames = res.data
      })
    },
    generate() {
      generateBankData(this.listQuery).then((res) => {
        if (res && res.rscode === '100000') {
          this.ifShowMessage = true
          this.$refs.uploadLoadSuccess.getSuccessNum()
         
        } else {
          this.upload_load = false
          this.ifShowMessage = false
          this.$parent.handleGenerateBtnLoading()
        }
        
      }).catch(() => {
         this.upload_load = false
         this.ifShowMessage = false
        uploadClose()
      })
    },
    // 上传
    upload() {
      uploadBankData(this.listQuery).then((res) => {
        this.listQuery.agencyId =''
        if (res && res.rscode === '100000') {
          this.ifShowMessage = true
          this.$refs.uploadLoadSuccess.getSuccessNum()
        } else {
          this.upload_load = false
          this.ifShowMessage = false
          this.$parent.handleUploadBtnLoading()
          this.$emit('handleUploadBtnLoading')
        }
      })
        .catch(() => {
          this.upload_load = false
          this.ifShowMessage = false
          uploadClose()
          
          
        })
       
    },
    // 撤销上传
    regenerate() {
      
      ungenerateBankData(this.listQuery)
        .then(() => {
          this.$message({
            message: '撤销上传成功',
            type: 'success',
            showClose: true,
            duration: 4000
          })
          this.handleFilter()
          this.$parent.handleRegenerateBtnLoading()
          // this.$emit('handleRegenerateBtnLoading')
        })
        .catch(() => {
          this.$parent.handleRegenerateBtnLoading()
          // this.$emit('handleRegenerateBtnLoading')
        })
        // })
        // .catch(() => {
        //   this.$parent.handleRegenerateBtnLoading()
        //   // this.$emit('handleRegenerateBtnLoading')
        // })
    },
    // 设置初始选中行
    setCurrent(flag) {
      if (this.tabPane === '2' && flag) {
        this.$refs.singleTable.setCurrentRow(this.list[1])
      } else {
        this.$refs.singleTable.setCurrentRow()
      }
    },
    // 选中行
    handleCurrentChange(row) {
      if (row) {
        this.agencyId = row.agencyId
      }
    },
    // 树的点击事件
    handleTree(data) {
      this.agencyId = data.id
      this.handleFilter()
    },
    // 切换树是否显示
    toggerTree() {
      this.treeShow = !this.treeShow
    },
    // 导出银行数据
    exportSalaryData() {
      const province = this.$store.getters.userInfo.province
      const fileName = 'salaryDataFile'
      const salaCardBank = this.listQuery.salaCardBank
      exportSalaryData(fileName, province,salaCardBank).then((response) => {
        const link = document.createElement('a')
        const objectUrl = URL.createObjectURL(response)
        link.href = objectUrl
        link.download = '银行数据.zip'
        link.click()
        URL.revokeObjectURL(objectUrl)
        this.$parent.exportCallback()
        // this.$emit('exportCallback')
      }).catch(() => {
        this.$parent.exportCallback()
        // this.$emit('exportCallback')
      })
    },
    query(salaCardBank, agencyBankLists) {
      this.agencyBankLists = agencyBankLists
      this.listQuery.salaCardBank = salaCardBank
      this.getProgresss()
      // this.personListQuery.salaCardBank = salaCardBank
      this.getList()
     // this.getPersonList()
    },
    fullscreen() {
      this.isFullScreen = true
    },
    exitFullscreen() {
      this.isFullScreen = false
    },
    // 获取勾选的数据data
    handleSelectionChange(val) {
        this.selected_list = val;
      
      },
    //自定义合计
    getSummaries(param) {    
        const { columns, data } = param;      
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计';
            return;
          }
          if (index <6) {
            return;
          }
          let values;
          values = data.map(item => Number(item[column.property])); // 无勾选
          if (this.selected_list && this.selected_list.length > 0) { // 有勾选
          values = this.selected_list.map(item => Number(item[column.property]));
            }
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if(index!=8){
              sums[index]= Number(sums[index]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
              sums[index] += ' 元';
            }else{
              sums[index] += ' 人';
            }
           
          } else {
            sums[index] = 'N/A';
          }
        });
    
        return sums;
      }
  }
}
</script>

<style lang="scss" scoped>
// .size.el-pagination.is-background .btn-prev,
// .el-pagination.is-background .btn-next {
//   width: 15px !important;
// }
  .full-screen {
    z-index: 9999;
    background: #fff;
    position: fixed;
    padding: 20px;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }
  .messagestyle {
    width: 110px;
    text-align: justify;
    display: inline-block;
    overflow: hidden;
    vertical-align: top;
  }
  .messagestyle:after {
    display: inline-block;
    width: 100%;
    content: " ";
    height: 0px;
  }
</style>
